package model

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"math"
	"order/internal/svc"
	"time"
)

type Order struct {
	gorm.Model
	OrderNo     string  `json:"order-no" gorm:"type:varchar(30);"`
	UserId      int     `json:"user-id" gorm:"type:int(11);"`
	GoodsId     int     `json:"goods-id" gorm:"type:int(11);"`
	OrderNum    int     `json:"order-num" gorm:"type:int(11);"`
	OrderPrice  float64 `json:"order-price" gorm:"type:decimal(10,2);"`
	OrderStatus int     `json:"order-status" gorm:"type:tinyint(1);"`
	CreatedAt   string  `json:"created-at" gorm:"type:varchar(20);"`

	ctx    context.Context     `gorm:"-"`
	svcCtx *svc.ServiceContext `gorm:"-"`
}

func NewOrderModel(ctx context.Context, svcCtx *svc.ServiceContext) *Order {
	return &Order{ctx: ctx, svcCtx: svcCtx}
}

func (o *Order) CreateOrder(userId, goodsId int) (info *Order, err error) {
	return info, WithMysql(func(db *gorm.DB) error {
		orderNo := uuid.NewString()
		info.OrderNo = orderNo

		var goods Goods

		db.Table("goods").Where("goods_id =?", goodsId).First(&goods)

		if goods.GoodsStock < 0 || goods.GoodsStock < info.OrderNum {
			return fmt.Errorf("商品库存不足")
		}
		return db.Transaction(func(tx *gorm.DB) error {
			info.OrderNum = goods.GoodsStock
			abs := math.Abs(float64(goods.GoodsStock) * goods.GoodsPrice)
			info.OrderPrice = abs
			return tx.Table("orders").Create(&info).Error
		})
	})
}

func (o *Order) OrderStatusTake(no string) (info *Order, err error) {
	return info, WithMysql(func(db *gorm.DB) error {
		db.Table("orders").Where("order_no=?", no).First(&info)

		time.Sleep(time.Hour * 3)
		if info.OrderStatus == 0 {
			return db.Table("orders").Where("order_no=?", no).Update("order_status", 1).Error
		}

		db.Callback()

		return db.Table("orders").Where("order_no=?", no).First(&info).Error
	})
}

func (o *Order) OrderCreated(page, pageSize int) (info []Order, err error) {
	return info, WithMysql(func(db *gorm.DB) error {
		offset := (page - 1) * pageSize

		return db.Table("orders").Limit(pageSize).Offset(offset).Order("created_at desc").Find(&info).Error

	})
}
